package com.example.casper.jnuexperiment2025;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class BookDetailsActivity extends AppCompatActivity {

    private EditText nameEdit, priceEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_edit_layout);

        nameEdit = findViewById(R.id.et_book_name);
        priceEdit = findViewById(R.id.et_book_price);
        Button saveBtn = findViewById(R.id.btn_save);

        Intent intent = getIntent();
        if ("update".equals(intent.getStringExtra("operation"))) {
            Book book = intent.getParcelableExtra("book");
            if (book != null) {
                nameEdit.setText(book.getName());
                priceEdit.setText(String.valueOf(book.getPrice()));
            }
        }

        saveBtn.setOnClickListener(v -> saveData());
    }

    private void saveData() {
        String name = nameEdit.getText().toString();
        String priceStr = priceEdit.getText().toString();

        if (name.isEmpty() || priceStr.isEmpty()) {
            // 可以添加提示信息
            return;
        }

        double price = Double.parseDouble(priceStr);
        Intent intent = getIntent();
        String operation = intent.getStringExtra("operation");

        Intent result = new Intent();

        if ("add".equals(operation)) {
            // 创建新图书 - 不需要强制类型转换，因为 Book 已经实现了 Parcelable
            Book newBook = new Book(System.currentTimeMillis(), name, price, R.drawable.book_no_name);
            result.putExtra("book", newBook);
        } else if ("update".equals(operation)) {
            // 修改现有图书
            Book originalBook = intent.getParcelableExtra("book");
            int position = intent.getIntExtra("position", -1);

            if (originalBook != null) {
                originalBook.setName(name);
                originalBook.setPrice(price);
                result.putExtra("book", originalBook);
                result.putExtra("position", position);
            }
        }

        result.putExtra("operation", operation);
        setResult(Activity.RESULT_OK, result);
        finish();
    }
}